//
//  XATitleView.swift
//  XAPageViewDemo
//
//  Created by XangAm on 2017/12/28.
//  Copyright © 2017年 Lan. All rights reserved.
//

import UIKit

protocol XATitleViewDelegate : class{
    
    func titleView(_ titleView : XATitleView,selectedIndex : Int) ->Void
    
}

class XATitleView: UIView {
    typealias ColorRGB = (r : CGFloat ,g : CGFloat ,b : CGFloat)//rgb元祖的别名
    open weak var delegate : XATitleViewDelegate? = nil
    
    fileprivate var style : XAPageViewStyle
    fileprivate var titles : [String]
    fileprivate var btns : [UIButton]
    fileprivate var selectedBtn : UIButton? = nil
    fileprivate var lastBtn    : UIButton? = nil
    
    fileprivate lazy var sourceRGB  : ColorRGB = style.titleViewSelectedColor.RGB
    fileprivate lazy var targetRGB  : ColorRGB = style.titleViewNormalColor.RGB
    
    //哈哈哈
    fileprivate lazy var detalRGB   : ColorRGB = {
        let r : CGFloat = sourceRGB.r - targetRGB.r
        let g : CGFloat = sourceRGB.g - targetRGB.g
        let b : CGFloat = sourceRGB.b - targetRGB.b
        return (r,g,b)
    }()
    fileprivate lazy var scrollView : UIScrollView = {
        let scrollView = UIScrollView(frame: self.bounds)
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator   = false
        scrollView.scrollsToTop = false
        scrollView.isScrollEnabled = style.titleViewIsScroll
        return scrollView
    }()
    fileprivate lazy var bottomLineView : UIView =  {
        let bottomLineView = UIView()
        bottomLineView.isHidden = style.bottomLineHidden
        bottomLineView.backgroundColor   = style.bottomLineBgColor
        bottomLineView.frame.size.height = style.bottomLineHeight
        bottomLineView.frame.origin.y    = bounds.height - style.bottomLineHeight
        return bottomLineView
    }()
    
    init(frame : CGRect,style : XAPageViewStyle,titles : [String]){
        
        self.style = style
        self.titles = titles
        self.btns   = [UIButton]()
        super.init(frame: frame)
        
        setupSubviews()
    }

    required init?(coder aDecoder: NSCoder) {
        return nil
    }
    
}

//MARK: - Setup
extension XATitleView {
    
   fileprivate  func setupSubviews(){
       
        guard titles.count > 0 else{
            return
        }
        
        //添加子控件
        addSubview(scrollView)
        scrollView.addSubview(bottomLineView)
        
        //创建btns
        for (i,title) in titles.enumerated(){
            let btn   = UIButton(type: .custom)
            btn.setTitle(title, for: .normal)
            btn.setTitleColor(style.titleViewNormalColor, for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: style.titleViewFontSize)
            btn.addTarget(self, action: #selector(btnSelectdAction(_:)), for: .touchUpInside)
            let btnSize = btn.sizeThatFits(btn.frame.size)
            //如果scrollView可以滚动btn.width = btn自身的宽度 + margin,反之btn.width = titleView均分
            let width   = style.titleViewIsScroll ? btnSize.width + style.titleViewMargin : bounds.width / CGFloat(titles.count) ,x : CGFloat = (i == 0 ? 0 : btns[i - 1].frame.maxX)
            btn.frame   = CGRect(x: x , y: 0, width:width , height: style.titleViewH)
            btns.append(btn)
//            btn.backgroundColor = UIColor.rondomColor
            scrollView.addSubview(btn)
        }
        scrollView.contentSize.width = btns.last!.frame.maxX
        selectedItem(btn: btns.first!)
    }
}

//MARK: - Action
extension XATitleView {
    
    @objc private func btnSelectdAction(_ btn : UIButton){
        
        selectedItem(btn: btn)
    }
}


//MARK: - Deal
extension XATitleView {
    
    fileprivate func selectedItem(btn : UIButton){
        guard let selectedIndex = btns.index(of: btn) else {
            return
        }
        if selectedBtn == btn{
            return
        }
        dealSelectedBtnStauts(btn)
        adjustBtnAsCenter(btn)
        
        //代理回调
        delegate?.titleView(self, selectedIndex: selectedIndex)
        
    }
    
    fileprivate func dealSelectedBtnStauts(_ selectedBtn : UIButton){
     
        self.selectedBtn = selectedBtn
        selectedBtn.setTitleColor(style.titleViewSelectedColor, for: .normal)
        lastBtn?.setTitleColor(style.titleViewNormalColor, for: .normal)
        UIView.animate(withDuration: 0.25, animations: {
            self.bottomLineView.frame.origin.x   = selectedBtn.frame.minX + self.style.titleViewMargin / 2
            self.bottomLineView.frame.size.width = selectedBtn.frame.width - self.style.titleViewMargin
            self.selectedBtn?.transform = CGAffineTransform(scaleX: self.style.maxScale, y: self.style.maxScale)
            self.lastBtn?.transform     = CGAffineTransform.identity
        })
        lastBtn = selectedBtn
    }
    
    fileprivate func adjustBtnAsCenter(_ selectedBtn : UIButton){
        //求出contentOffset,让selectedBtn居中显示
        var contentOffsetX = selectedBtn.center.x - (bounds.width  * 0.5)
        //边界值的判断
        let minCritical : CGFloat = 0
        let maxCritical : CGFloat = max(scrollView.contentSize.width - bounds.width, 0)
        contentOffsetX = min(max(minCritical, contentOffsetX), maxCritical)
        scrollView.setContentOffset(CGPoint(x: contentOffsetX, y: 0), animated: true)
        
    }
}

//MARK: - <XAContentViewDelegate>
extension XATitleView : XAContentViewDelegate{
    func contentView(_ contentView : XAContentView?,selectedIndex : Int) ->Void{
        guard selectedIndex < titles.count else{
            return
        }
        let btn =  btns[selectedIndex]
        dealSelectedBtnStauts(btn)
        adjustBtnAsCenter(btn)
    }
    
    func contentView(_ contentView : XAContentView?,contentViewScrolling  selectedIndex : Int ,nextIndex : Int,progress : CGFloat) ->Void{
        //titleView的渐变事件
        
        //设置文字渐变颜色
        let sourceBtn = btns[selectedIndex]
        let targetBtn = btns[nextIndex]

        let sourceColor = UIColor(r: sourceRGB.r - detalRGB.r * progress, g: sourceRGB.g - detalRGB.g * progress, b: sourceRGB.b - detalRGB.b * progress)
        let targetColor = UIColor(r: targetRGB.r + detalRGB.r * progress, g: targetRGB.g + detalRGB.g * progress, b: targetRGB.b + detalRGB.b * progress)
        sourceBtn.setTitleColor(sourceColor, for: .normal)
        targetBtn.setTitleColor(targetColor, for: .normal)
        
        
        //设置Scale的渐变
//        let scaleDetal = style.maxScale - 1
//        let sourceScale = style.maxScale -  scaleDetal * progress
//        let targetScale = 1 + scaleDetal * progress
//        sourceBtn.transform = CGAffineTransform(scaleX: sourceScale, y: sourceScale)
//        targetBtn.transform = CGAffineTransform(scaleX: targetScale, y: targetScale)
        
        //设置bottomLineFrame渐变
        let sourceBtnW = sourceBtn.frame.width - style.titleViewMargin
        let targetBtnBtnW = targetBtn.frame.width - style.titleViewMargin
        let sourceBtnX    = sourceBtn.frame.minX + self.style.titleViewMargin / 2
        let targetBtnBtnX = targetBtn.frame.minX + self.style.titleViewMargin / 2
        let bottomLineViewWDetal = targetBtnBtnW - sourceBtnW
        let bottomLineViewXDetal = targetBtnBtnX - sourceBtnX
        let bottomLineViewW = sourceBtnW + bottomLineViewWDetal * progress
        let bottomLineViewX = sourceBtnX + bottomLineViewXDetal * progress
        bottomLineView.frame.origin.x   = bottomLineViewX
        bottomLineView.frame.size.width = bottomLineViewW
    }
}


//MARK: - <XASectionPageViewDelegate>
extension XATitleView : XASectionPageViewDelegate{
    func sectionPageView(_ sectionPageView : XASectionPageView,selectedIndex : Int) ->Void{
       self.contentView(nil, selectedIndex: selectedIndex)
    }
}


